package com.eight.cloud.auth.common.security.authentication;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;

import java.util.Collection;

/**
 * 多租户用户登陆
 *
 * @ClassName: TenantUsernamePasswordAuthenticationToken
 * @Author: TXC
 * @Date: 2024-12-23 16:38
 **/
public class TenantUsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    /**
     * 用户名
     */
    private final Object principal;
    /**
     * 凭证
     */
    private Object credentials;
    /**
     * 租户id
     */
    private final Object tenantId;

    public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials, Object tenantId) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        this.tenantId = tenantId;
        setAuthenticated(false);
    }

    public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials, Object tenantId,
                                                     Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        this.tenantId = tenantId;
        super.setAuthenticated(true);
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        Assert.isTrue(!isAuthenticated,
                "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

    @Override
    public Object getCredentials() {
        return this.credentials;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.credentials = null;
    }

    public Object getTenantId() {
        return this.tenantId;
    }

    public static TenantUsernamePasswordAuthenticationToken unauthenticated(Object principal, Object credentials, Object tenantId) {
        return new TenantUsernamePasswordAuthenticationToken(principal, credentials, tenantId);
    }
}
